package com.demo.youxuanmall.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${spring.web.resources.static-locations}")
    private String staticLocations;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Autowired
    private LoginInterceptor loginInterceptor;

    @PostConstruct
    public void init() {
        // 创建上传目录
        String projectPath = System.getProperty("user.dir");
        // 创建商品图片目录
        String productImageDir = projectPath + "/upload/images";
        File productDir = new File(productImageDir);
        if (!productDir.exists()) {
            productDir.mkdirs();
        }
        // 创建用户头像目录
        String avatarDir = projectPath + "/upload/avatars";
        File avatarDirFile = new File(avatarDir);
        if (!avatarDirFile.exists()) {
            avatarDirFile.mkdirs();
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置商品图片访问路径
        registry.addResourceHandler("/upload/images/**")
                .addResourceLocations("file:" + System.getProperty("user.dir") + "/upload/images/");
        
        // 配置用户头像访问路径
        registry.addResourceHandler("/upload/avatars/**")
                .addResourceLocations("file:" + System.getProperty("user.dir") + "/upload/avatars/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**");  // 拦截所有请求，在拦截器内部判断是否需要登录
    }
} 